class Article < ActiveRecord::Base
  
  acts_as_taggable
  belongs_to :tag
  belongs_to :user
  belongs_to :category
    belongs_to :categoryt
 belongs_to :websitesinf
       has_many :photos
  has_many :imageurls       
  has_many :comments       
  validates_presence_of :title
  validates_presence_of :synopsis
  validates_presence_of :body
  validates_presence_of :imageurl  
 
#  validates_uniqueness_of :title
  validates_length_of :title, :maximum => 255
  validates_length_of :synopsis, :maximum => 10000


  before_save :update_published_at,:update_user_published_by

  def update_published_at
	  if published == true
	    self.published_at = Time.now 
	  else
	    self.published_at = nil
	  end
  end

  def published_authorized_for_update?
    current_user.has_role?('administrator')
  end
  
  def published_authorized_for_create?
    current_user.has_role?('administrator')    
  end
  
    def user_published_by_authorized_for_update?
    current_user.has_role?('administrator') 
  end  
    def user_published_by_authorized_for_update?
    (current_user.has_role?('administrator'))&&!(self.published)    
  end  
  
  def update_user_published_by
    if self.user_published_by.nil?
	    curraliasn = Ualia.find_by_iscurrent(true)
	    if !curraliasn.nil?
	      self.user_published_by = curraliasn.name	  
      end
    end
  end
  
  def before_create
    self.created_by = current_user.name
    self.user_id = current_user.id
  end  
  
    def before_update
    self.last_updated_at = Time.now
    self.last_updated_user = current_user.name
  end
  
   def has_websitesinf?(websitename)
    self.websitesinfs.find_by_name(websitename) ? true : false
  end  
  
    protected
  def validate
      errors.add(:category_id, "Please select a category!") if category_id.nil? || category_id < 0 
  end
end
